package day36.edu;

import org.junit.Test;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

// Created: 06/10/2025, ChangJiang Ru
public class TcpTest {
    @Test
    // Client
    public void test1() {
        Socket socket = null;
        OutputStream os = null;
        try {
            // Create a Socket
            InetAddress inetAddress = InetAddress.getByName("192.168.199.211"); // ip
            int port = 8989; // port

            socket = new Socket(inetAddress, port);

            // output data
            os = socket.getOutputStream();
            os.write("Do you everyday english and programming".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // close Socket
            try {
                if (socket != null)
                    socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (socket != null)
                    os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }

    @Test
    // Server
    public void test2() {
        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream is = null;
        try {
            // Create a server Socket
            int port = 8989;
            serverSocket = new ServerSocket(port);

            // call accept(), receive socket of client
            socket = serverSocket.accept();
            System.out.println("Receiving the host is :" + socket.getInetAddress().getHostAddress() + " of data");

            // input data
            is = socket.getInputStream();
            byte[] buffer = new byte[1024];
            int len;
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            while((len = is.read(buffer)) != -1)
            {
/*
                String str = new String(buffer, 0, len);
                System.out.print(str);
*/
                baos.write(buffer, 0, len);
            }
            System.out.println(baos.toString());

            System.out.println("nReceiving the data successfully");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // close socket and ServerSocket
            try {
                if (socket != null)
                    socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            /*try {
                if (serverSocket != null)
                    serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }*/
            try {
                if(is != null)
                    is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }



    }
}
